const {
  userServerError,
  userAlreadyExsitd,
  userDoesNotExsit,
  updatePwdErr,
} = require("../constant/err.type");
const {
  createUser,
  checkUserDoesExsit,
  checkUserLogin,
  changePwd,
} = require("../service/user.service");
const { USER_SECRET } = require("../config/config.default");
const jwt = require("jsonwebtoken");
class UserController {
  // 用户注册控制器
  async register(ctx, next) {
    const { username, password, phone } = ctx.request.body;
    // 操作数据库
    try {
      if (await checkUserDoesExsit(username)) {
        ctx.app.emit("error", userAlreadyExsitd, ctx);
        return;
      }
      const result = await createUser(username, password, phone);
      console.log("res", result);
      if (result.code === "10002") {
        ctx.response.status = 409;
      }
      if (result) {
        ctx.response.body = result;
        next();
      }
    } catch (error) {
      console.log(error);
      ctx.app.emit("error", userServerError, ctx);
    }
  }
  // 用户登录控制器
  async login(ctx, next) {
    const { username, password } = ctx.request.body;
    try {
      if (await checkUserDoesExsit(username)) {
        const res = await checkUserLogin(username, password);
        const token = jwt.sign(res, USER_SECRET, {
          expiresIn: "1h",
          // 测试 10 秒
          // expiresIn: 10,
        });
        ctx.response.body = {
          code: "10000",
          message: `登录成功`,
          data: {
            token,
          },
        };
        // return
      } else {
        ctx.app.emit("error", userDoesNotExsit, ctx);
      }
    } catch (error) {}
  }
  //修改密码
  async updatePwd(ctx, next) {
    const { id } = ctx.state;
    const { password: pwd } = ctx.request.body;
    if (await changePwd(id, pwd)) {
      ctx.response.body = {
        code: "0",
        message: "修改密码成功",
        data: null,
      };
    } else {
      ctx.app.emit("error", updatePwdErr, ctx);
    }
  }
}

module.exports = new UserController();
